﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Utility;
using System.Net;
using System.Net.Mail;
using System.Threading;
using Components;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private string from = "Lattice_Call_Plan@deya.cn";
        private string to = "";
        private string week = "";
        private string weekDay = "";
        private bool isTest = false;

        public Form1()
        {
            InitializeComponent();
            AccessDb db = new AccessDb("Database2.mdb");
            DataTable dt = db.Query("SELECT MSysObjects.Name FROM MSysObjects WHERE (((MSysObjects.Name) Not Like \"MSys*\") AND ((MSysObjects.Type)=1)) ORDER BY MSysObjects.Name DESC");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                String dName = dt.Rows[i]["Name"].ToString();
                if(!dName.Contains("MSys"))
                    cbTable.Items.Add(dName);
            }
            cbTable.SelectedIndex = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (cbTable.SelectedItem.ToString() == "")
            {
                MessageBox.Show("请选择Table");
                return;
            }
            AccessDb db = new AccessDb("Database2.mdb");
            DataTable dt = db.Query("select * from " + cbTable.SelectedItem.ToString() + " where email not in('(空白)', '总计')");
            //email not in('(空白)', '总计')
            week = cbWeek.Text;
            weekDay = cbWeekDay.Text;
            to = comboBox1.Text;
            isTest = false;
            this.button1.Enabled = false;
            backgroundWorker1.RunWorkerAsync(dt);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (cbTable.SelectedItem.ToString() == "")
            {
                MessageBox.Show("请选择Table");
                return;
            }
            if (tbTestIDs.Text == "")
            {
                MessageBox.Show("请填写TestIDs");
                return;

            }
            AccessDb db = new AccessDb("Database2.mdb");
            DataTable dt = db.Query("select * from " + cbTable.SelectedItem.ToString() + " where id in(" + tbTestIDs.Text + ")");//3,30,58,86
            to = comboBox1.Text;
            week = cbWeek.Text;
            weekDay = cbWeekDay.Text;
            isTest = true;
            this.button2.Enabled = false;
            backgroundWorker1.RunWorkerAsync(dt);
        }

        //临时
        private void button3_Click(object sender, EventArgs e)
        {
            string mailFrom = "delledm@deya.cn";
            string fromName = "Brand_and_I活动组";
            string mailTo = "maggie_chen@deya.cn";//maggie_chen@deya.cn
            string subject = "Brand and I第三期礼品发放事宜";
            string message = "<div style=\"font-family:FZZhunYuan-M02S, 方正准圆简体; font-size:10.5pt; line-height:16.5pt; color:#244061;\">Dear 小伙伴们，<br><br>";
            message += "恭喜您获得Brand and I 第三期活动礼品——精美U盘一个！<br>";
            message += "在CCC5的小伙伴们，我们将于2014年1月23日中午11:30-12:00在CCC5大楼门口处，开始发放U盘，还请带上伙伴们的工牌过来领取哦！谢谢。<br>";
            message += "在CCC2的小伙伴们，我们将于2014年1月24日中午11:30-12:00在CCC2食堂入口处，开始发放U盘，还请带上伙伴们的工牌过来领取哦！谢谢。<br>";
            message += "若不在厦门office的小伙伴们，还请大家在此邮件基础上回复各位0ffice的地址哦，我们将安排寄送到其他地区0ffice。<br><br>";
            message += "万分感谢大家的配合！<br><br>";
            message += "  <table border=\"0\" cellspacing=\"1\" cellpadding=\"0\" bgcolor=\"#000000\">";
            message += "  <tr>";
            message += "    <td width=\"76\" height=\"30\" valign=\"top\" bgcolor=\"#FFFFFF\"><p> 姓名 </p></td>";
            message += "    <td width=\"241\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>地址 </p></td>";
            message += "    <td width=\"109\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>联系电话 </p></td>";
            message += "    <td width=\"194\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>邮箱 </p></td>";
            message += "  </tr>";
            message += "  <tr>";
            message += "    <td width=\"76\" height=\"30\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>&nbsp; </p></td>";
            message += "    <td width=\"241\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>&nbsp; </p></td>";
            message += "    <td width=\"109\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>&nbsp; </p></td>";
            message += "    <td width=\"194\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>&nbsp; </p></td>";
            message += "  </tr>";
            message += "</table><br>";
            message += "<span style=\"color:#e36c0a;\">小伙伴们，新年快乐！2014新征程，让我们相伴前行，共迎新的明天！</span></div>";
            sendmail(mailFrom, fromName, mailTo, subject, message);
        }
        private void button2_Click_1(object sender, EventArgs e)
        {
            string mailFrom = "delledm@deya.cn";
            string fromName = "Brand_and_I活动组";
            string subject = "Brand and I第三期礼品发放事宜";
            string message = "<div style=\"font-family:FZZhunYuan-M02S, 方正准圆简体; font-size:10.5pt; line-height:16.5pt; color:#244061;\">Dear 小伙伴们，<br><br>";
            message += "恭喜您获得Brand and I 第三期活动礼品——精美U盘一个！<br>";
            message += "在CCC5的小伙伴们，我们将于2014年1月23日中午11:30-12:00在CCC5大楼门口处，开始发放U盘，还请带上伙伴们的工牌过来领取哦！谢谢。<br>";
            message += "在CCC2的小伙伴们，我们将于2014年1月24日中午11:30-12:00在CCC2食堂入口处，开始发放U盘，还请带上伙伴们的工牌过来领取哦！谢谢。<br>";
            message += "若不在厦门office的小伙伴们，还请大家在此邮件基础上回复各位0ffice的地址哦，我们将安排寄送到其他地区0ffice。<br><br>";
            message += "万分感谢大家的配合！<br><br>";
            message += "  <table border=\"0\" cellspacing=\"1\" cellpadding=\"0\" bgcolor=\"#000000\">";
            message += "  <tr>";
            message += "    <td width=\"76\" height=\"30\" valign=\"top\" bgcolor=\"#FFFFFF\"><p> 姓名 </p></td>";
            message += "    <td width=\"241\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>地址 </p></td>";
            message += "    <td width=\"109\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>联系电话 </p></td>";
            message += "    <td width=\"194\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>邮箱 </p></td>";
            message += "  </tr>";
            message += "  <tr>";
            message += "    <td width=\"76\" height=\"30\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>&nbsp; </p></td>";
            message += "    <td width=\"241\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>&nbsp; </p></td>";
            message += "    <td width=\"109\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>&nbsp; </p></td>";
            message += "    <td width=\"194\" valign=\"top\" bgcolor=\"#FFFFFF\"><p>&nbsp; </p></td>";
            message += "  </tr>";
            message += "</table><br>";
            message += "<span style=\"color:#e36c0a;\">小伙伴们，新年快乐！2014新征程，让我们相伴前行，共迎新的明天！</span></div>";
            AccessDb db = new AccessDb("Database2.mdb");
            DataTable dt = db.Query("select * from mg3");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string email = dt.Rows[i]["email"].ToString();
                sendmail(mailFrom, fromName, email, subject, message);
                Thread.Sleep(10000);
            }
        }

        private void sendmail(string mailFrom, string displayName, string mailTo, string subject, string messgae)
        {
            SmtpClient _smtpClient = new SmtpClient();
            _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; //指定电子邮件发送方式
            _smtpClient.Host = "smtp.qiye.163.com";//指定SMTP服务器
            _smtpClient.Credentials = new NetworkCredential(mailFrom, "deya2012");//用户名和密码  

            MailMessage _mailMessage = new MailMessage(mailFrom, mailTo);
            _mailMessage.Subject = (isTest ? "[Testing]" : "") + subject;//主题
            _mailMessage.Body = messgae;//内容
            _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码
            _mailMessage.IsBodyHtml = true;//设置为HTML格式
            _mailMessage.Priority = MailPriority.High;//优先级
            //Attachment att = new Attachment(filename);
            //_mailMessage.Attachments.Add(att);
            _mailMessage.From = new MailAddress(mailFrom, displayName);
            _mailMessage.Sender = new MailAddress(mailFrom, displayName);

            try
            {
                _smtpClient.Send(_mailMessage);
                LogService.Log("Smtp sent to " + mailTo);
            }
            catch (Exception ex)
            {
                LogService.ErrorLog("Utility:Smtp:Send() To:"+mailTo, ex);
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if(week==""){
                MessageBox.Show("请选择截止WK");
                return;
            }
            if (weekDay == "")
            {
                MessageBox.Show("请选择截止WK Day");
                return;
            }
            String endDate = week + "-" + weekDay;

            BackgroundWorker worker = sender as BackgroundWorker;
            DataTable dt = (DataTable)e.Argument;
            int count = dt.Rows.Count;
            for (int i = 0; i < count; i++)
            {
                string email = dt.Rows[i]["email"].ToString();
                string email2 = dt.Rows[i]["email2"].ToString();
                string email3 = dt.Rows[i]["email3"].ToString();
                string a1 = dt.Rows[i]["a1"].ToString();
                string a2 = dt.Rows[i]["a2"].ToString();
                string a3 = dt.Rows[i]["a3"].ToString();
                string a4 = dt.Rows[i]["a4"].ToString();
                string a5 = dt.Rows[i]["a5"].ToString();
                string a6 = dt.Rows[i]["a6"].ToString();

                double d5 = Convert.ToDouble(a5.Replace("%", ""));
                double d6 = Convert.ToDouble(a6.Replace("%", ""));

                string mailSubject = "";
                string mailMessage = "";
                string filename = "att" + (from == "Lattice_Call_Plan@deya.cn" ? "1" : "2") + "\\" + email + ".xlsx";
                string mailTo = isTest ? to : email + "@dell.com";
                if (isTest)
                {
                    email2 = "";
                    email3 = "";
                }
                else
                {
                    email2 = email2 == "" ? "" : email2 + "@dell.com";
                    email3 = email3 == "" ? "" : email3 + "@dell.com";
                }

                    mailSubject = "【温馨提醒】目前您尚有未完成的Lattice call plan目标，请及时跟进。";
                    if (d5 < 8.0)
                        a5 = "<span style=\"background:red;\">" + a5 + "</span>";
                    else if (d5 < 10.0)
                        a5 = "<span style=\"background:yellow;\">" + a5 + "</span>";
                    else
                        a5 = "<span style=\"background:lime;\">" + a5 + "</span>";

                    if (d6 < 38.4)
                        a6 = "<span style=\"background:red;\">" + a6 + "</span>";
                    else if (d6 < 48.0)
                        a6 = "<span style=\"background:yellow;\">" + a6 + "</span>";
                    else
                        a6 = "<span style=\"background:lime;\">" + a6 + "</span>";

                    mailMessage += "<div style=\"font-family:FZZhunYuan-M02S, 方正准圆简体; font-size:10.5pt; line-height:16.5pt; color:#244061;\">亲爱的销售同事，<br><br>";
                    mailMessage += "<span style=\"color:red;\">截止<b>" + endDate + "</b>, ";
                    if (a2 == "0")
                    {
                        mailMessage += "您的Lattice call plan已全部跟进完毕，暂无新增call plan。</span><br><br>";
                    }
                    else
                    {
                        mailMessage += "本季度您已完成<b>" + a1 + "</b>个Lattice call plan ，剩余<b>" + a2 + "</b>个尚未跟进。</span><br><br>";
                    }
                    mailMessage += "本季度您有<b>" + a3 + "</b>个Lattice call plan，目前的<b>Follow % = " + a4 + "</b>, 本季度的目标为<b>95%</b><br>";
                    mailMessage += "同时，您的<b>Conversion % = " + a5 + "</b>, 本季度的目标为<b>10%</b></div>";
                    mailMessage += "<div style=\"font-family:FZZhunYuan-M02S, 方正准圆简体; font-size:10.5pt; line-height:16.5pt; text-indent:60.25pt; color:#244061;\"><b>Win% = " + a6 + "</b>, 本季度的目标为<b>48%</b><br>详见附件。</div><br><br><br>";

                    mailMessage += "<div style=\"font-family:FZZhunYuan-M02S, 方正准圆简体; font-size:9.0pt; line-height:16.5pt; color:#244061;\"><b>备注：</b>Conversion % 定义 : 已建立或关联的Pipeline个数 / 已跟进的Plan个数</div>";
                    mailMessage += "<div style=\"font-family:FZZhunYuan-M02S, 方正准圆简体; font-size:9.0pt; line-height:16.5pt; text-indent:31.5pt; color:#244061;\">Win % 定义 : Win pipeline rev / Total pipeline rev</div>";
                    mailMessage += "<div style=\"font-family:FZZhunYuan-M02S, 方正准圆简体; font-size:9.0pt; line-height:16.5pt; text-indent:31.5pt; color:#244061;\">Win pipeline rev 定义: Stage 为 100% 的Pipeline rev</div>";
                    mailMessage += "<div style=\"font-family:FZZhunYuan-M02S, 方正准圆简体; font-size:9.0pt; line-height:16.5pt; text-indent:31.5pt; color:#244061;\">Pipeline 定义: 已经和Campaign关联的Funnel</div>";
                
                SmtpClient _smtpClient = new SmtpClient();
                _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; //指定电子邮件发送方式
                _smtpClient.Host = "smtp.qiye.163.com";//指定SMTP服务器
                _smtpClient.Credentials = new NetworkCredential(from, "deya2012");//用户名和密码

                //如果上面的不能成功可以将发送方式该为下面这一句
                // _smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;   

                MailMessage _mailMessage = new MailMessage(from, mailTo);
                if(email2!="")
                    _mailMessage.CC.Add(email2);
                if (email3 != "")
                    _mailMessage.CC.Add(email3);
                _mailMessage.Subject = (isTest ? "[Testing]" : "") + mailSubject;//主题
                _mailMessage.Body = mailMessage;//内容
                _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码
                _mailMessage.IsBodyHtml = true;//设置为HTML格式
                _mailMessage.Priority = MailPriority.High;//优先级
                Attachment att = new Attachment(filename);
                _mailMessage.Attachments.Add(att);
                _mailMessage.Sender = new MailAddress(from, from == "Lattice_Call_Plan@deya.cn" ? "Lattice Call Plan" : "Relationship Leads");

                try
                {
                    _smtpClient.Send(_mailMessage);
                    LogService.Log("Smtp sent to " + mailTo);
                }
                catch (Exception ex)
                {
                    LogService.ErrorLog("Utility:Smtp:Send()", ex);
                }
                int percentComplete = (int)((float)(i + 1) / (float)count * 100);
                worker.ReportProgress(percentComplete);
                Thread.Sleep(10000);
            }
            if (isTest)
            {
                this.button1.Enabled = true;
            }
            else
            {
                this.button2.Enabled = true;
            }
            MessageBox.Show("发送完成");
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                //resultLabel.Text = "Canceled";
            }
            else
            {
                //resultLabel.Text = e.Result.ToString();
            }
        }

        /// <summary>  
        /// 取指定日期是一年中的第几周
        /// </summary>  
        /// <param name="dtime">给定的日期</param>
        public static int weekofyear(DateTime dtime)
        {
            int weeknum = 0;
            DateTime tmpdate = DateTime.Parse(dtime.Year.ToString() + "-1" + "-1");
            DayOfWeek firstweek = tmpdate.DayOfWeek;
            //if(firstweek)
            int i = dtime.DayOfYear - 1 + (int)firstweek;
            weeknum = i / 7;
            if (i > 0)
            {
                weeknum++;
            }
            return weeknum;
        }
    }
}
